﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using DAL.Models;
using DAL.BAL;
using DevExpress.Xpf.Editors.Settings;
using DevExpress.Xpf.Grid;
using DevExpress.Xpf.Editors;
using DevExpress.Xpf.Core;
using DevExpress.Xpf.Bars;
using System.IO;


namespace WpfClient.Windows
{
    /// <summary>
    /// Interaction logic for CandidateEdit.xaml
    /// </summary>
    public partial class CandidateEdit : Window
    {
        private Candidate candidate = null;

        public CandidateEdit(Candidate candidate, bool isNew, bool canSave)
        {
            InitializeComponent();

            this.candidate = candidate;

            if (isNew)
            {
                this.Title = "Новый кандидат";

                this.ceIsCandidat.IsChecked = true;
            }
            else
                this.Title = candidate.LastName;

            if (!Business.CanEditFieldManager())
            {
                if (isNew)
                    this.candidate.User = Business.currentUser;

                cbManager.IsReadOnly = true;
            }

            if (Business.CanInsertCandidatesAsContactPersons())
            {
                candidate.IsContactPerson = true;

                candidate.IsCandidate = false;

                ceIsCandidat.IsReadOnly = true;

                ceIsContactPerson.IsReadOnly = true;
            }

            this.DataContext = this.candidate;

            bOk.SetVisible(canSave);

            lgContacts.SetVisible(Business.CanSeeCandidateContacts());

            if (isNew)
                this.candidate.EnterDate = DateTime.Today;

            #region init datasources

            cbManager.ItemsSource = Business.GetUsers().ToList();

            ((ComboBoxEditSettings)gridExceptEmployers.Columns["Employer"].EditSettings).ItemsSource = Business.GetEmployersLookUP().ToList();

            ((ComboBoxEditSettings)gridExceptCommodityGroups.Columns["CommodityGroup"].EditSettings).ItemsSource = Business.GetCommodityGroups().ToList();

            var positions = Business.GetPositions().ToList();

            ((ComboBoxEditSettings)gridExpirienceHistory.Columns["Position"].EditSettings).ItemsSource = positions;

            ((ComboBoxEditSettings)gridCandidatePositions.Columns["Position"].EditSettings).ItemsSource = positions;

            ((ComboBoxEditSettings)gridCandidateHistory.Columns["InterviewResult"].EditSettings).ItemsSource = LoadedData.InterviewResults;

            var territories = Business.GetTerritories().ToList();

            ((ComboBoxEditSettings)gridCandidateRangeTerritory.Columns["Territory"].EditSettings).ItemsSource = territories;

            cbTeritory.ItemsSource = territories;

            cbSalaryRange.ItemsSource = LoadedData.SalaryRanges;

            cbCar.ItemsSource = LoadedData.HasCars;

            cbType.ItemsSource = LoadedData.Candidate_Types;

            cbSex.ItemsSource = Business.GetSexVariants(false);

            cbPosition_priority.ItemsSource = LoadedData.CompareImportants;

            cbSalaryRange_priority.ItemsSource = LoadedData.CompareImportants;

            cbTeritoryVac_priority.ItemsSource = LoadedData.CompareImportants;

            #endregion

            if (isNew)
            {
                this.candidate.CompareImportant2 = (from n in Business.dosvidEntities.CompareImportants
                                                    where n.Id == 1
                                                    select n).FirstOrDefault();

                cbTeritoryVac_priority.SelectedIndex = 1;
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if ((candidate.User != null) && (candidate.LastName != null) &&
                (candidate.LastName != string.Empty) && (candidate.EnterDate != null) && (candidate.SexVariant != null) &&
                candidate.Candidate_Types != null)
            {
                this.DialogResult = true;

                this.Close();
            }
            else
                MessageBox.Show(WpfClient.Properties.Resources.ThereAreMandatoryFields, WpfClient.Properties.Resources.Error, MessageBoxButton.OK, MessageBoxImage.Warning);
        }

        private void deDate_Validate(object sender, ValidationEventArgs e)
        {
            if (e.Value == null || e.Value.ToString() == string.Empty)
            {
                e.IsValid = false;

                e.ErrorContent = WpfClient.Properties.Resources.Field_Cant_Be_Empty;
            }

        }

        private void deleteRowItemCG_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (MessageBox.Show(WpfClient.Properties.Resources.AreYouSureYouWantDelete,
                    WpfClient.Properties.Resources.Warning, MessageBoxButton.YesNoCancel, MessageBoxImage.Warning) == MessageBoxResult.Yes)
            {

                gridPhones.View.CommitEditing();

                DAL.Models.Candidat_Phones ec = (DAL.Models.Candidat_Phones)gridPhones.GetRow(gridPhones.View.FocusedRowHandle);
                               
                (gridPhones.View as GridViewBase).DeleteRow(gridPhones.View.FocusedRowHandle);
                
                if (ec != null)
                    Business.DeleteObject(ec);
            }

        }

        private void deleteRowItemExpHist_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (MessageBox.Show(WpfClient.Properties.Resources.AreYouSureYouWantDelete,
                  WpfClient.Properties.Resources.Warning, MessageBoxButton.YesNoCancel, MessageBoxImage.Warning) == MessageBoxResult.Yes)
            {
                gridExpirienceHistory.View.CommitEditing();

                DAL.Models.Candidat_Expiriences ec = (DAL.Models.Candidat_Expiriences)gridExpirienceHistory.GetRow(gridExpirienceHistory.View.FocusedRowHandle);

                (gridExpirienceHistory.View as GridViewBase).DeleteRow(gridExpirienceHistory.View.FocusedRowHandle);

                if (ec != null)
                    Business.DeleteObject(ec);
            }
        }

        private void deleteRowEmails_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (MessageBox.Show(WpfClient.Properties.Resources.AreYouSureYouWantDelete,
                  WpfClient.Properties.Resources.Warning, MessageBoxButton.YesNoCancel, MessageBoxImage.Warning) == MessageBoxResult.Yes)
            {

                gridEmails.View.CommitEditing();

                DAL.Models.Candidat_EMails ec = (DAL.Models.Candidat_EMails)gridEmails.GetRow(gridEmails.View.FocusedRowHandle);

                (gridEmails.View as GridViewBase).DeleteRow(gridEmails.View.FocusedRowHandle);

                if (ec != null)
                    Business.DeleteObject(ec);
            }

        }

        private void beResume_DefaultButtonClick(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.FileName = string.Empty;
            dlg.DefaultExt = ".doc;.docx";
            dlg.Filter = "Word documents (.doc,.docx)|*.doc;*.docx";

            Nullable<bool> result = dlg.ShowDialog();

            if (result == true)
            {
                try
                {
                    if (candidate.Candidate_Resume.Count == 0)
                    {
                        Candidate_Resume candidateResume = new Candidate_Resume();
                        candidateResume.CandidateID = candidate.Id;
                        candidateResume.Resume = File.ReadAllBytes(dlg.FileName);

                        candidate.Candidate_Resume.Add(candidateResume);
                    }
                    else
                    {
                        candidate.Candidate_Resume.FirstOrDefault().Resume = File.ReadAllBytes(dlg.FileName);
                    }
                    candidate.ResumeName = System.IO.Path.GetFileName(dlg.FileName);
                }
                catch (Exception e1)
                {
                    MessageBox.Show(e1.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }

            }
        }

        private void btLoad_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (candidate.Candidate_Resume != null)
                {
                    Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                    dlg.FileName = candidate.ResumeName;
                    dlg.DefaultExt = System.IO.Path.GetExtension(candidate.ResumeName);
                    dlg.Filter = "Word documents (.doc,.docx)|*.doc;*.docx";

                    // Show save file dialog box
                    Nullable<bool> result = dlg.ShowDialog();


                    // Process save file dialog box results
                    if (result == true)
                    {
                         System.IO.File.WriteAllBytes(dlg.FileName, candidate.Candidate_Resume.FirstOrDefault().Resume);
                    }
                }
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message, WpfClient.Properties.Resources.Error, MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void deleteRowItemCanHist_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (MessageBox.Show(WpfClient.Properties.Resources.AreYouSureYouWantDelete,
                WpfClient.Properties.Resources.Warning, MessageBoxButton.YesNoCancel, MessageBoxImage.Warning) == MessageBoxResult.Yes)
            {

                gridCandidateHistory.View.CommitEditing();

                DAL.Models.Candidat_VacancyHistory ec = (DAL.Models.Candidat_VacancyHistory)gridCandidateHistory.GetRow(gridCandidateHistory.View.FocusedRowHandle);

                (gridCandidateHistory.View as GridViewBase).DeleteRow(gridCandidateHistory.View.FocusedRowHandle);

                if (ec != null)
                    Business.DeleteObject(ec);
            }

        }

        private void deleteRowItemExcEmplo_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (MessageBox.Show(WpfClient.Properties.Resources.AreYouSureYouWantDelete,
                 WpfClient.Properties.Resources.Warning, MessageBoxButton.YesNoCancel, MessageBoxImage.Warning) == MessageBoxResult.Yes)
            {

                gridExceptEmployers.View.CommitEditing();

                DAL.Models.Candidat_ExceptEmployers ec = (DAL.Models.Candidat_ExceptEmployers)gridExceptEmployers.GetRow(gridExceptEmployers.View.FocusedRowHandle);

                (gridExceptEmployers.View as GridViewBase).DeleteRow(gridExceptEmployers.View.FocusedRowHandle);

                if (ec != null)
                    Business.DeleteObject(ec);
            }

        }

        private void deleteRowItemExcComG_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (MessageBox.Show(WpfClient.Properties.Resources.AreYouSureYouWantDelete,
                WpfClient.Properties.Resources.Warning, MessageBoxButton.YesNoCancel, MessageBoxImage.Warning) == MessageBoxResult.Yes)
            {

                gridExceptCommodityGroups.View.CommitEditing();

                DAL.Models.Candidat_ExceptCommodityGroups ec = (DAL.Models.Candidat_ExceptCommodityGroups)gridExceptCommodityGroups.GetRow(gridExceptCommodityGroups.View.FocusedRowHandle);

                (gridExceptCommodityGroups.View as GridViewBase).DeleteRow(gridExceptCommodityGroups.View.FocusedRowHandle);

                if (ec != null)
                    Business.DeleteObject(ec);
            }

        }

        private void btOpen_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (Environment.GetEnvironmentVariable("Temp") != string.Empty)
                {
                    if (candidate.Candidate_Resume != null)
                    {
                        string fileName = string.Format("{0}{1}", Environment.GetEnvironmentVariable("Temp"), candidate.ResumeName);

                        System.IO.File.WriteAllBytes(fileName, candidate.Candidate_Resume.FirstOrDefault().Resume);

                        System.Diagnostics.Process process = new System.Diagnostics.Process();

                        process.StartInfo.FileName = fileName;

                        process.Start();

                    }
                }
                else
                    MessageBox.Show(WpfClient.Properties.Resources.TherIsNotTempFolder, WpfClient.Properties.Resources.Warning, MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message, WpfClient.Properties.Resources.Error, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void TableView_ValidateRow(object sender, GridRowValidationEventArgs e)
        {
            if (((DAL.Models.Candidat_Expiriences)e.Row).Position == null)
            {
                e.ErrorContent = WpfClient.Properties.Resources.Field_Cant_Be_Empty + " (" +
                                 gridExpirienceHistory.Columns["Position"].Header + ")";
                e.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning;
                e.IsValid = false;

            }
            else
                if (((DAL.Models.Candidat_Expiriences)e.Row).Years == 0)
                {
                    e.ErrorContent = WpfClient.Properties.Resources.Field_Cant_Be_Empty + " (" +
                                     gridExpirienceHistory.Columns["Years"].Header + ")";
                    e.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning;
                    e.IsValid = false;

                }
                else
                    e.IsValid = true;
        }

        private void TableView_InvalidRowException(object sender, InvalidRowExceptionEventArgs e)
        {
            e.ExceptionMode = ExceptionMode.NoAction;
        }

        private void gridEmails_ValidateRow(object sender, GridRowValidationEventArgs e)
        {
            if ((((DAL.Models.Candidat_EMails)e.Row).EMail == null) ||
                (((DAL.Models.Candidat_EMails)e.Row).EMail == string.Empty))
            {
                e.ErrorContent = WpfClient.Properties.Resources.Field_Cant_Be_Empty + " (" +
                                 gridEmails.Columns["EMail"].Header + ")";
                e.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning;
                e.IsValid = false;

            }
            else
                e.IsValid = true;
        }

        private void gridPhones_ValidateRow(object sender, GridRowValidationEventArgs e)
        {
            if ((((DAL.Models.Candidat_Phones)e.Row).Phone == null) ||
                (((DAL.Models.Candidat_Phones)e.Row).Phone == string.Empty))
            {
                e.ErrorContent = WpfClient.Properties.Resources.Field_Cant_Be_Empty + " (" +
                                 gridPhones.Columns["Phone"].Header + ")";
                e.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning;
                e.IsValid = false;

            }
            else
                e.IsValid = true;
        }

        private void gridExceptEmployers_ValidateRow(object sender, GridRowValidationEventArgs e)
        {
            if (((DAL.Models.Candidat_ExceptEmployers)e.Row).Employer == null)
            {
                e.ErrorContent = WpfClient.Properties.Resources.Field_Cant_Be_Empty + " (" +
                                 gridExceptEmployers.Columns["Employer"].Header + ")";
                e.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning;
                e.IsValid = false;

            }
            else
                e.IsValid = true;
        }

        private void gridExceptCommodityGroups_ValidateRow(object sender, GridRowValidationEventArgs e)
        {
            if (((DAL.Models.Candidat_ExceptCommodityGroups)e.Row).CommodityGroup == null)
            {
                e.ErrorContent = WpfClient.Properties.Resources.Field_Cant_Be_Empty + " (" +
                                 gridExceptCommodityGroups.Columns["CommodityGroup"].Header + ")";
                e.ErrorType = DevExpress.XtraEditors.DXErrorProvider.ErrorType.Warning;
                e.IsValid = false;

            }
            else
                e.IsValid = true;

        }

        private void deleteRowItemCandidate_position_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (MessageBox.Show(WpfClient.Properties.Resources.AreYouSureYouWantDelete,
         WpfClient.Properties.Resources.Warning, MessageBoxButton.YesNoCancel, MessageBoxImage.Warning) == MessageBoxResult.Yes)
            {

                gridCandidatePositions.View.CommitEditing();

                DAL.Models.Candidate_Positions ec = (DAL.Models.Candidate_Positions)gridCandidatePositions.GetRow(gridCandidatePositions.View.FocusedRowHandle);

                (gridCandidatePositions.View as GridViewBase).DeleteRow(gridCandidatePositions.View.FocusedRowHandle);

                if (ec != null)
                    Business.DeleteObject(ec);
            }

        }

        private void deleteRowItemCandidate_RangeTerritory_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (MessageBox.Show(WpfClient.Properties.Resources.AreYouSureYouWantDelete,
            WpfClient.Properties.Resources.Warning, MessageBoxButton.YesNoCancel, MessageBoxImage.Warning) == MessageBoxResult.Yes)
            {

                gridCandidateRangeTerritory.View.CommitEditing();

                DAL.Models.Candidat_RangeTerritories ec = (DAL.Models.Candidat_RangeTerritories)gridCandidateRangeTerritory.GetRow(gridCandidateRangeTerritory.View.FocusedRowHandle);

                (gridCandidateRangeTerritory.View as GridViewBase).DeleteRow(gridCandidateRangeTerritory.View.FocusedRowHandle);

                if (ec != null)
                    Business.DeleteObject(ec);
            }

        }

        private void ceIsCandidat_EditValueChanged(object sender, EditValueChangedEventArgs e)
        {
            if ((bool)e.NewValue == false)
                if (ceIsContactPerson.IsChecked == false)
                {
                    ceIsContactPerson.IsChecked = true;
                    
                }
        }

        private void ceIsContactPerson_EditValueChanged(object sender, EditValueChangedEventArgs e)
        {
            if ((bool)e.NewValue == false)
            {
                ceSendContacts.Visibility = System.Windows.Visibility.Hidden;
                if (ceIsCandidat.IsChecked == false)
                    ceIsCandidat.IsChecked = true;
            }
            ceSendContacts.Visibility = System.Windows.Visibility.Visible;
        }

        private void gridCandidateHistory_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            OpenVacancyInfo();
        }

        private void OpenVacancyInfo()
        {
            Candidat_VacancyHistory hist = (Candidat_VacancyHistory)gridCandidateHistory.GetFocusedRow();

            if (hist != null)
            {
                Vacancy vacancy = (from n in Business.GetVacancies()
                                   where n.Id == hist.Vacancy.Id
                                   select n).FirstOrDefault();

                if (vacancy != null)
                    new VacancyEdit(vacancy, false, false).ShowDialog();
            }
        }

        private void vacancyInfo_ItemClick(object sender, ItemClickEventArgs e)
        {
            OpenVacancyInfo();
        }
        
    }
}
